import { trim, isEmpty } from 'lodash';
import { Op } from 'sequelize';
import BaseController from './base';
import MiniTicketModel from '../models/mini-ticket';
import UserModel from '../models/user';
import dayjs from 'dayjs';
import { validationResult } from 'express-validator';
import { getSequelize } from '../db';
import ExpressValidationError from '../utils/validation-error';
import { getHotel } from '../utils';


// order docs https://sequelize.org/docs/v6/core-concepts/model-querying-basics/
class SmsLogController extends BaseController {
  constructor() {
    super();
    this.resolve = this.resolve.bind(this);
  }

  getModel() {
    return MiniTicketModel;
  }

  /**
   * 解析查询条件
   * @returns {Object}
   */
  getFindWhere(req) {
    const {
      dates, status, description
    } = req.query;
    const { hotel_id } = req.user;

    const where = { hotel_id };
    if (Array.isArray(dates) && dates.length === 2) {
      where.created_at = {
        [Op.gte]: dayjs(dates[0]).toISOString(),
        [Op.lt]: dayjs(dates[1]).add(1, 'days').toISOString(),
      };
    }

    if (status) {
      where.status = status;
    }

    if (description) {
      where.description = {
        [Op.like]: `%${trim(description)}%`
      };
    }

    return { where };
  }

  getInclude() {
    return {
      include: [{
        model: UserModel,
        as: 'updater'
      }]
    }
  }

  async create(req, res, next) {
    try {
      const { openid } = req.headers;
      const result = validationResult(req);
      if (!result.isEmpty()) {
        throw new ExpressValidationError({ errors: result.array() });
      }

      // this.formatter(req);
      const model = this.getModel();
      const hotel = await getHotel(req);
      req.body.hotel_id = hotel.id;
      req.body.openid = openid;
      req.body.ip_address = req.clientIPV4;

      if (Array.isArray(req.body.images)) {
        for (let index = 0; index < req.body.images.length; index++) {
          req.body[`image${index + 1}`] = req.body.images[index].url;
        }
      }

      const transaction = await getSequelize().transaction();
      req.transaction = transaction;
      const data = await model.create(req.body, { req, transaction });
      await transaction.commit();
      res.sendOk(data);
    }
    catch (e) {
      next(e);
    }
  }

  async resolve(req, res, next) {
    try {
      const { id } = req.params;
      const { body } = req;
      const db = getSequelize();
      const model = this.getModel();
      const transaction = await db.transaction();
      const instance = await model.findOne({ where: { id }, transaction, rejectOnEmpty: new Error('数据不存在') });
      if (instance.status === 'Closed') {
        throw new Error('反馈已关闭, 无法重复操作');
      }

      instance.setDataValue('comment', body.comment);
      instance.setDataValue('status', 'Closed');
      instance.setDataValue('closed_at', dayjs().toISOString());
      instance.setDataValue('updated_id', req.user.id);

      const data = await instance.save({ transaction, req });

      await transaction.commit();
      res.sendOk(data);
    }
    catch (e) {
      next(e);
    }
  }
}

export default new SmsLogController();
